const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const BluetoothLockDevice = require('./BluetoothLockDevice');

const BluetoothLockOpenRecord = sequelize.define('BluetoothLockOpenRecord', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  lockId: {
    type: DataTypes.STRING(255),
    allowNull: false
  },
  active: {
    type: DataTypes.BOOLEAN,
    allowNull: true,
    defaultValue: true
  },
  lng: {
    type: DataTypes.FLOAT,
    allowNull: true
  },
  lat: {
    type: DataTypes.FLOAT,
    allowNull: true
  },
  dis: {
    type: DataTypes.FLOAT,
    allowNull: true
  },
  position: {
    type: DataTypes.STRING(255),
    allowNull: false
  },
  remark: {
    type: DataTypes.STRING(255),
    allowNull: true
  },
  opDate: {
    type: DataTypes.DATE,
    allowNull: true
  },
  alias: {
    type: DataTypes.STRING(255),
    allowNull: true
  },
  oName: {
    type: DataTypes.STRING(255),
    allowNull: true
  },
  username: {
    type: DataTypes.STRING(255),
    allowNull: true
  },
  deviceId: {
    type: DataTypes.STRING(255),
    allowNull: true
  },
  operatingTime: {
    type: DataTypes.DATE,
    allowNull: true
  },
  name: {
    type: DataTypes.STRING(255),
    allowNull: true
  },
  model: {
    type: DataTypes.STRING(255),
    allowNull: true
  },
  department: {
    type: DataTypes.STRING(255),
    allowNull: true
  },
  lockStatus: {
    type: DataTypes.STRING(255),
    allowNull: true
  },
  startTime: {
    type: DataTypes.DATE,
    allowNull: true
  },
  endTime: {
    type: DataTypes.DATE,
    allowNull: true
  }
}, {
  timestamps: true,
  createdAt: 'createdAt',
  updatedAt: 'updatedAt',
  startTime: 'startTime',
  endTime: 'endTime'
});

// 建立关联关系
BluetoothLockOpenRecord.belongsToMany(BluetoothLockDevice, {
  through: 'BluetoothLockOpenRecordDevices',
  foreignKey: 'recordId',
  otherKey: 'deviceId'
});

BluetoothLockDevice.belongsToMany(BluetoothLockOpenRecord, {
  through: 'BluetoothLockOpenRecordDevices',
  foreignKey: 'deviceId',
  otherKey: 'recordId'
});

// 同步模型到数据库
BluetoothLockOpenRecord.sync({ alter: true }).then(() => {
  console.log('BluetoothLockOpenRecord table has been updated');
}).catch(err => {
  console.error('Error updating BluetoothLockOpenRecord table:', err);
});

module.exports = BluetoothLockOpenRecord; 